package tw.rescue.controller.slim3.message;

import idv.mylee.web.slim3.TidyHotReloadFactory;
import org.apache.commons.lang.xwork.StringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;

import tw.rescue.cache.slim3.Slim3MemcacheUtil;
import tw.rescue.dao.CategoryDao;
import tw.rescue.model.slim3.meta.CategoryMeta;
import tw.rescue.model.slim3.model.Account;
import tw.rescue.model.slim3.model.Category;
import tw.rescue.util.JspUtil;

@SuppressWarnings("unchecked")
public abstract class HouseKeepingController extends Controller {

	/**
	 * Prepare commonly used request attributes for jsp
	 * @return
	 */
	@Override
	protected Navigation setUp() {
		JspUtil.setup(request);
		request.setAttribute("template", "default");
		return super.setUp();
	}

	/**
	 * Create Account entity of current user from request cookie
	 * @return
	 */
	protected Account asAccount() {
		// TODO
		return null;
	}
	
	/**
	 * Create Category entity from request parameter
	 * @return
	 */
	protected Category asCategory() {
		String ctg = asString("category");
		if (StringUtils.isBlank(ctg))
			return null;
		CategoryDao dao = null;
		try {
			dao = (CategoryDao)TidyHotReloadFactory.getBean("categoryDao");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (dao==null)
			throw new RuntimeException("Can not find categoryDao bean");
		Key key = Datastore.createKey(CategoryMeta.get(), ctg);
		Category category = (Category)new Slim3MemcacheUtil<Category>().get(Category.KIND, key, dao); 
		return category;
	}
}
